#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
更新数据库中的密码哈希值
这个脚本用于修复数据库中错误的密码哈希值
"""

import pymysql
from werkzeug.security import generate_password_hash

# 数据库配置
db_config = {
    'host': 'localhost',
    'user': 'root',
    'password': 'gyx20050818!',  # 修改为你的MySQL密码
    'database': 'campus_assistant',
    'charset': 'utf8mb4'
}

def update_passwords():
    """更新数据库中的密码哈希值"""
    try:
        # 连接数据库
        conn = pymysql.connect(**db_config, cursorclass=pymysql.cursors.DictCursor)
        
        with conn.cursor() as cursor:
            # 获取所有用户
            cursor.execute("SELECT id, username FROM students")
            users = cursor.fetchall()
            
            print(f"找到 {len(users)} 个用户，开始更新密码哈希...")
            
            # 为每个用户生成正确的密码哈希
            for user in users:
                # 默认密码为 123456
                password_hash = generate_password_hash('123456')
                
                # 更新密码哈希
                cursor.execute(
                    "UPDATE students SET password = %s WHERE id = %s",
                    (password_hash, user['id'])
                )
                
                print(f"已更新用户 {user['username']} 的密码哈希")
            
            # 提交更改
            conn.commit()
            print("\n所有密码哈希更新完成！")
            print("现在所有用户的默认密码都是: 123456")
            print("\n用户列表:")
            
            # 显示所有用户信息
            cursor.execute("SELECT username, name, is_admin FROM students")
            users = cursor.fetchall()
            
            for user in users:
                role = "管理员" if user['is_admin'] else "学生"
                print(f"- 用户名: {user['username']}, 姓名: {user['name']}, 角色: {role}")
                
    except Exception as e:
        print(f"错误: {e}")
    finally:
        if 'conn' in locals():
            conn.close()

if __name__ == '__main__':
    print("=== 密码哈希更新工具 ===")
    print("这个工具将把所有用户的密码重置为 123456")
    
    confirm = input("确认要继续吗？(y/N): ")
    if confirm.lower() in ['y', 'yes', '是']:
        update_passwords()
    else:
        print("操作已取消")